var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
const {
  requestDataparams
} = require('../../utils/request.js');
const {showLoading,hideLoading} = require('../../utils/util.js');
Page({
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    dishesList: '',
    restaurantId: 1,
    isScheduled: '',
    scheduledTime: '',
    orderType: '',
    hasDiff:'',
    goods: [],
    restaurantEvaluations: [],
    restaurantintro: {},
    currentTab: 0, //选择项目、选择技师、优惠券
    currentLeft: 0, //左侧选中的下标
    selectId: "item2", //当前显示的元素id
    scrollTop: 0, //到顶部的距离
    serviceTypes: [], //项目列表数据
    staffList: [],
    coupons: [],
    currenttab: 1,
    isAddCar: 0,
    totalPackingCharges: 0,
    id: wx.getStorageSync("id"),
    token: wx.getStorageSync("TOKEN"),
    bannerlist: [{
        picurl: applet_park_api_url_imgUrl+'/ctimg1.png',
      },
      {
        picurl: applet_park_api_url_imgUrl+'/ctimg2.png',
      },
      {
        picurl: applet_park_api_url_imgUrl+'/ctimg2.png',
      }
    ],
    heightArr:[],
    distance:0,
    toView: '0',
    scrollTop: 100,
    foodCounts: 0,
    totalPrice: 0, // 总价格
    totalCount: 0, // 总商品数
    carArray: [],//购物车
    minPrice: 15, //起送價格
    payDesc: '去结算',
    clicked:'',
    fold: true,
    selectFoods: [{
      price: 20,
      count: 2
    }],
    cartShow: 'none',
    status: 0,
    url: "",
    showPopup: false,
    Time:[],
  },
  selectMenu: function(e) {
    var index = e.currentTarget.dataset.itemIndex;
    this.setData({
      toView: 'order' + index.toString()
    })
  },
  selectact(e) {
    this.setData({
      currenttab: e.currentTarget.dataset.index
    })
  },
  //移除商品
  decreaseCart: function(e) {
    // var index = e.currentTarget.dataset.index;
    // var parentIndex = e.currentTarget.dataset.pos;
    let foodsimg = e.currentTarget.dataset.foodsimg
    // this.data.goods[parentIndex].foods[index].Count--
    //   var name = this.data.goods[parentIndex].foods[index].name;
    // var num = this.data.goods[parentIndex].foods[index].Count;
    // var mark = 'a' + index + 'b' + parentIndex
    // var price = this.data.goods[parentIndex].foods[index].price;
    let foodid = e.currentTarget.dataset.foodid;
    let parentid = e.currentTarget.dataset.parentid;
    var packingCharges = e.currentTarget.dataset.packingcharges;
    let that = this;
    let goodslist = that.data.goods;
    for (var itema of goodslist) {
      if (itema.id == parentid) {
        for (let itemb of itema.foods) {
          if (itemb.recipesDishId == foodid) {
            if(itemb.Count >= 0){
              itemb.Count--;
            }else{
               return false;
            }
            var mark = 'a-' + foodid + 'b-' + parentid;
            let num = itemb.Count;
            var price = itemb.price;
            var name = itemb.name;
            var openingTime = itemb.openingTime;
            var endTime = itemb.endTime;
            var packingCharges = itemb.packingCharges;
            var obj = {
              price: price,
              num: num,
              mark: mark,
              name: name,
              foodsimg: foodsimg,
              foodid: foodid,
              parentid: parentid,
              openingTime: openingTime,
              endTime: endTime,
              packingCharges: packingCharges,
            };
            var carArray1 = that.countShoppingCars(mark,obj,num)

            for (var m = 0; m < carArray1.length; m++) {
              if (carArray1[m].num == 0) {
                carArray1.splice(m, 1); // splice(a,b); a需要删除的位置,b删除几个
              }
            }
            this.setData({
              carArray: carArray1,
              goods: this.data.goods
            })

            this.calTotalPrice()
            this.setData({
              payDesc: this.payDesc(),
            })
            //关闭弹起
            var count1 = 0
            for (let i = 0; i < carArray1.length; i++) {
              if (carArray1[i].num == 0) {
                count1++;
              }
            }
            if (count1 == carArray1.length) {
              if (num == 0) {
                this.setData({
                  cartShow: 'none'
                })
              }
            }
            this.shoppingCarts(foodid, parentid, num,openingTime,endTime)

          }
        }
      }
    }
  },

  decreaseShopCart: function(e) {
    this.decreaseCart(e);
  },
  countShoppingCars(mark,obj,num){
      var carArray1 = this.data.carArray;
      if(carArray1.length == 0){
        carArray1.push(obj)
      }else{
        var result = false
        for(var i=0; i<carArray1.length; i++){
          if(mark == carArray1[i].mark ){
            carArray1[i].num = num;
            result = true
            break
          }
        }
        if(!result){
          carArray1.push(obj)
        }
    }
    return carArray1;
  },
  //添加到购物车
  addCart(e) {
    var that = this;
    // var index = e.currentTarget.dataset.index;
    // var parentIndex = e.currentTarget.dataset.pos;
    let foodsimg = e.currentTarget.dataset.foodsimg
    let foodid = e.currentTarget.dataset.foodid;
    let parentid = e.currentTarget.dataset.parentid;
    let goodslist = this.data.goods;
    var openingTime =  e.currentTarget.dataset.openingtime;
    var endTime = e.currentTarget.dataset.endtime;
    var parentName = e.currentTarget.dataset.parentname;
    var packingCharges = e.currentTarget.dataset.packingcharges;
    if((openingTime) && (endTime)){
      //  if(this.time_range (openingTime, endTime)){
      for (var itema of goodslist) {

        if (itema.id == parentid) {
          for (let itemb of itema.foods) {
            if (itemb.recipesDishId == foodid) {
              itemb.Count++;
              var mark = 'a-' + foodid + 'b-' + parentid;
              var price = itemb.price;
              var num = itemb.Count;
              var name = itemb.name;
              var openingTime = itemb.openingTime;
              var endTime = itemb.endTime;
              var packingCharges = itemb.packingCharges;
              var obj = {
                price: price,
                num: num,
                mark: mark,
                name: name,
                foodsimg: foodsimg,
                foodid: foodid,
                parentid: parentid,
                openingTime: openingTime,
                endTime: endTime,
                packingCharges: packingCharges
              };
              //var carArray1 = this.data.carArray.filter(item => item.mark != mark)
              that.shoppingCarts(foodid, parentid, num,openingTime,endTime);
              var carArray1 = that.countShoppingCars(mark,obj,num)
                this.setData({
                  carArray: carArray1,
                  goods: this.data.goods
                })
                this.calTotalPrice();
                this.setData({
                  payDesc: this.payDesc()
                })
              
             
            }
          }
        }
      }
      this.setData({
        goods: this.data.goods
      })
    // }else{
    //   var title = '您所选择的菜品包含'+parentName+'分类，因时间原因,请重新选择';
    //    wx.showToast({
    //      title: title,
    //      icon:'none'
    //    })
    // }
    }
    
  },
  addShopCart: function(e) {
    this.addCart(e);
  },

  // 加入购物车后台
  shoppingCarts(foodid, parentid, num,openingTime,endTime) {
    let that = this;
    var id = app.globalData.id || wx.getStorageSync("id");
    var TOKEN = app.globalData.TOKEN || wx.getStorageSync("TOKEN");
    requestDataparams('/api/shoppingCarts', {
      sysUserId: id, 
      restaurantId: Number.parseInt(that.data.restaurantId),
      dishTypeId: parentid,
      dishId: foodid,
      number: num,
      scheduleTime: this.data.scheduledTime,
    }, 'POST').then(res => {
       if( res.data.code == 1){
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
        return false 
       }
        that.setData({
          isAddCar: res.data.code
        })
    }).catch(err => {
      
    });
  },
  //判断点餐时间
  time_range (beginTime, endTime) {
    var beginTime = beginTime.substring(0,5);
    var strb = beginTime.split (":");
    if (strb.length != 2) {
        return false;
    }
    var endTime = endTime.substring(0,5);
    var stre = endTime.split (":");
    if (stre.length != 2) {
        return false;
    }
    var b = new Date ();
    var e = new Date ();
    var n = new Date ();
    b.setHours (strb[0]);
    b.setMinutes (strb[1]);
    e.setHours (stre[0]);
    e.setMinutes (stre[1]);

    if (n.getTime () - b.getTime () >= 0 && n.getTime () - e.getTime () <= 0) {
        return true;
    } else {
        return false;
    }
},

  // 加载购物车
  loadshoppingCarts() {
    let that = this;
    var id = app.globalData.id || wx.getStorageSync("id");
    let data = {
      sysUserId: id,
      restaurantId: that.data.restaurantId,
    }
    requestDataparams('/api/shoppingCarts', data, 'GET').then(res => {
      if (res.data.code == 0) {
        if (res.data.data.length > 0) {

          let items = [];
          for (item of res.data.data) {
            item.foodsimg = that.Handleimg(item.image)[0]
            item.num = item.count;
            item.foodid = item.recipesDishId;
            item.mark = 'a-' + item.recipesDishId + 'b-' + item.parentid;
            items.push(item);
          }
          that.setData({
            carArray: items
          })
          that.setData({
            payDesc: that.payDesc()
          });

        }
      }else if( res.data.code == 1){
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
        return false
      }else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
        
      }
    }).catch(err => {
      
    });
    that.payDesc();
  },

  // 清空购物车
  clearshoppingCarts() {
    let that = this;
    var id = app.globalData.id || wx.getStorageSync("id");
    let url = '/api/shoppingCarts?sysUserId=' + id + '&restaurantId=' + that.data.restaurantId;
    requestDataparams(url, {}, 'DELETE').then(res => {

    }).catch(err => {
      
    });
  },
  //计算总价
  calTotalPrice: function() {
    var carArray = this.data.carArray;
    var totalPrice = 0;
    var totalCount = 0;
    for (var i = 0; i < carArray.length; i++) {
      totalPrice += carArray[i].price * carArray[i].num;
      totalCount += carArray[i].num
    }
    this.setData({
      totalPrice: totalPrice,
      totalCount: totalCount,
      payDesc: this.payDesc()
    });
  },
  //清空页面 包括总价 购物车数量
  empty() {
    this.toggleList();
    this.data.carArray = [];
    wx.clearStorageSync('carArray');
    let recipes = this.data.goods;
    for (let recipe of recipes) {
      for (let dish of recipe.foods) {
        dish.Count = 0;
      }
    }
    this.calTotalPrice();
    this.setData({
      payDesc: this.payDesc(),
      carArray: [],
      goods: this.data.goods
    })

    this.clearshoppingCarts();
    this.data.totalPrice = 0;
    this.data.totalCount = 0;
  },
  //差几元起送
  payDesc() {
    var that = this;
    if (that.data.totalPrice === 0) {
      return `￥${that.data.totalPrice}`;
    } else if (that.data.totalPrice < that.data.minPrice) {
      var  diff = that.data.totalPrice;
      that.setData({
        hasDiff:diff
      })
      return  diff;
    } else {
      return '去结算';
    }
  },

  //购物车
  toggleList: function() {
    if (!this.data.totalCount) {
      return;
    }
    this.setData({
      fold: !this.data.fold,
    })
    var fold = this.data.fold
    this.cartShow(fold)
  },
  cartShow: function(fold) {
    if (fold == false) {
      this.setData({
        cartShow: 'block',
      })
    } else {
      this.setData({
        cartShow: 'none',
      })
    }
  },
  godishsdetail(e) {
    wx.navigateTo({
      url: '../dishesDetail/dishesDetail?dishsid=' + e.target.dataset.dishsid,
    })
  },

  tabChange: function(e) {
    var showtype = e.target.dataset.type;
    this.setData({
      status: showtype,
    });
  },
  loadData() {//购物车数据
    var that = this;
    var id = app.globalData.id || wx.getStorageSync("id");
    wx.showLoading({
      title: '加载中',
    });
    requestDataparams('/api/dishTypes', {
      restaurantId: that.data.restaurantId,
      scheduledTime: that.data.scheduledTime,
    }, 'GET').then(res => {

      if (res.data.code == 0) {
        this.setData({
          Time: res.data.data.openingTime
        })
        res.data.data.restaurant.images = that.Handleimg(res.data.data.restaurant.images)
        // 获取购物车列表
        let certList = that.data.carArray;
        // 购物车数量数据
        requestDataparams('/api/shoppingCarts/numbers', {
          restaurantId: that.data.restaurantId,
          sysUserId: id
        }, 'GET').then(res2 => {
          // 根据购物车循环添加数量
          if (res2.data.code == 0 && res2.data.data) {
            if (res2.data.data.length != 0) {
              const certs = res2.data.data;
              const recipes = res.data.data.dishTypes;
              for (let recipe of recipes) {
                for (let dish of recipe.foods) {
                  dish.image = that.Handleimg(dish.image)
                  var carArray = wx.getStorageSync('carArray');
                  if(carArray){//如果从热门推荐菜品加购  需要先改变数量
                    for(var i=0;i<carArray.length;i++){
                        if(carArray[i].foodid == dish.id){
                          dish.Count = 1;
                        }
                    }
                  }
                  const count = certs[recipe.id + "-" + dish.recipesDishId]
                  dish.Count = dish.Count ? dish.Count : 0
                }
              }
              that.setData({
                goods: res.data.data.dishTypes,
                restaurantintro: res.data.data.restaurant
              })
              wx.hideLoading();

              that.calTotalPrice();
              that.selectHeight();
              that.setData({
                payDesc: that.payDesc()
              });
              that.setData({
                dishesList: ''
              })
            } else {
              const recipes = res.data.data.dishTypes
              for (let recipe of recipes) {
                for (let dish of recipe.foods) {
                  dish.image = that.Handleimg(dish.image)
                  dish.Count = 0;
                }
              }
              that.setData({
                goods: res.data.data.dishTypes,
                restaurantintro: res.data.data.restaurant
              })
              
              wx.hideLoading();
              that.calTotalPrice();
              that.selectHeight();
              that.setData({
                payDesc: that.payDesc()
              });
              that.setData({
                dishesList: '暂无内容'
              })
            }

          } else {
            const recipes = res.data.data.dishTypes
            for (let recipe of recipes) {
              for (let dish of recipe.foods) {
                dish.image = that.Handleimg(dish.image)
                dish.Count = 0;
              }
            }
            that.setData({
              goods: res.data.data.dishTypes,
              restaurantintro: res.data.data.restaurant
            })
            wx.hideLoading();
            that.calTotalPrice();
            that.selectHeight();
            that.setData({
              payDesc: that.payDesc()
            });
            that.setData({
              dishesList: '暂无内容'
            })
          }
        }).catch(err => {
          

          const recipes = res.data.data.dishTypes
          for (let recipe of recipes) {
            for (let dish of recipe.foods) {
              dish.images = that.Handleimg(dish.images)
              dish.Count = 0;
            }
          }
          that.setData({
            goods: res.data.data.dishTypes,
            restaurantintro: res.data.data.restaurant
          })
          wx.hideLoading();
          that.calTotalPrice();
          that.selectHeight();
          that.setData({
            payDesc: that.payDesc()
          });
        });



      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        });
        that.setData({
          dishesList: '暂无内容'
        })
        wx.hideLoading();
      }
    }).catch(err => {
      
    });

  },
  //加载评价数据
  loadrestaurantEvaluations() {
    var that = this;
    requestDataparams('/api/restaurantEvaluations', {
      restaurantId: that.data.restaurantId
    }, 'GET').then(res => {
      let restaurantEvaluations = [];
      if (res.data.code == 0) {
        for (let item of res.data.data) {
          if (item.images) {
            item.images = that.Handleimg(item.images);
          }
          restaurantEvaluations.push(item);
        }
        that.setData({
          restaurantEvaluations: restaurantEvaluations
        })

      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        });
      }
    }).catch(err => {
      
    });
  },

  Handleimg(e) {
    let imglist = e.split(",");
    let imglists = [];
    let url = applet_park_api_url_imgUrl;
    for (let item of imglist) {
      let list = url +'/'+ item
      imglists.push(list);
    }

    return imglists
  },
  onLoad: function(options) {
    if (options.scheduledTime) {
      this.data.scheduledTime = options.scheduledTime;
    }
    if (options.restaurantId) {
      this.data.restaurantId = options.restaurantId;
    }
    if (options.orderType) {
      this.data.orderType = options.orderType;
    }
    if (options.isScheduled) {
      this.data.isScheduled = options.isScheduled;
    }
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    if(prevPage.route != 'pages/dishesDetail/dishesDetail'){//热门菜品不需要清空购物车
      this.empty();
      wx.clearStorageSync('carArray')
      this.setData({
        payDesc: this.payDesc(),
        carArray: [],
      });
    }else{
      this.setData({
        payDesc: this.payDesc(),
        carArray: wx.getStorageInfoSync('carArray'),
      });
    }
    this.loadData();
    this.loadshoppingCarts();
    this.loadrestaurantEvaluations();
    this.setData({
      cartShow: 'none'
    })
    this.setData({
      carArray:[]
    })
    
    this.setData(this.data);
  },

  pay() {//结算 跳转页面
    var that = this;
    var id = app.globalData.id || wx.getStorageSync('id');
    if (!that.data.carArray > 0) {
      wx.showToast({
        title: '请先选菜',
        icon: 'none'
      })
      return false
    }
   if(that.data.totalPrice <= 0){
        wx.showToast({
          title: '您的购物车还是空的,请先点餐',
          icon: 'none'
        })
        return false
   }
   showLoading('加载中...');//防止重复提交
    let data = {
      sysUserId: id,
      restaurantId: that.data.restaurantId,
      orderType: that.data.orderType,
      scheduledTime: that.data.scheduledTime,
      isScheduled: that.data.isScheduled,
      totalAmount: parseInt(that.data.totalPrice)*100
    };
    requestDataparams('/api/restaurantOrders', data, 'POST').then(res => {
      if (res.data.code == 0) {
        wx.setStorageSync('carArray',that.data.carArray)
        wx.navigateTo({
          url: '../dishespay/dishespay?orderNo=' + res.data.data.orderNo + '&totalPrice=' + that.data.totalPrice +'&restaurantId='+that.data.restaurantId +'&orderType='+that.data.orderType,
        })
        hideLoading()
      } else {
        wx.showToast({
          title: '网络异常',
        })
      }
    }).catch(err => {
      
    });
    
  },
  onReady: function() {
    // 页面渲染完成
    var that = this;
    setTimeout(function() {
      that.selectHeight();
    }, 2000);
    that.setData({
      payDesc: that.payDesc()
    });
  },
  onShow: function() {
    // this.loadData();
    // this.loadshoppingCarts();
    // this.loadrestaurantEvaluations();
    // this.setData({
    //   cartShow: 'none'
    // })
    // this.setData({
    //   carArray:[]
    // })
    
    
    // 页面显示
  },
  onHide: function() {
    //this.empty();
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  //选择项目左侧点击事件 currentLeft：控制左侧选中样式  selectId：设置右侧应显示在顶部的id
  proItemTap(e) {
    this.setData({
      currentLeft: parseInt(e.currentTarget.dataset.pos),
      selectId: "item" + e.currentTarget.dataset.pos,
      clicked: 'clicked',
    })
  },

  //计算右侧每一个分类的高度，在数据请求成功后请求即可
  selectHeight() {

    let that = this;
    that.data.heightArr = [];
    let h = 0;
    const query = wx.createSelectorQuery();
    query.selectAll('.pro-box').boundingClientRect()
    query.exec(function(res) {
      res[0].forEach((item) => {
        h += item.height;
        that.data.heightArr.push(h);
      })
    })


  },

  //监听scroll-view的滚动事件
  scrollEvent(event) {
    var that = this;
    if (that.data.heightArr.length == 0) {
      return;
    }
    let scrollTop = event.detail.scrollTop;
    let current = that.data.currentLeft;
    if (scrollTop >= that.data.distance) { //页面向上滑动
      //如果右侧当前可视区域最底部到顶部的距离 超过 当前列表选中项距顶部的高度（且没有下标越界），则更新左侧选中项
      if (current + 1 < that.data.heightArr.length && scrollTop >=  that.data.heightArr[current]) {
        that.setData({
          currentLeft: current + 1
        })
      }
    } else { //页面向下滑动
      //如果右侧当前可视区域最顶部到顶部的距离 小于 当前列表选中的项距顶部的高度，则更新左侧选中项
      if (current - 1 >= 0 && scrollTop < that.data.heightArr[current]) {
        if(that.data.clicked == 'clicked'){//点击
          that.setData({
            currentLeft: current,
            clicked:'',
          })
        }else{
          if(scrollTop < that.data.heightArr[current-1]){
            that.setData({
              currentLeft: current - 1,
            })
          }
          
        }
        
      }
    }
    //更新到顶部的距离
    that.data.distance = scrollTop;
  },
  //滚动到指定名称的某一项（通过列表的商品name来判断，也可以用id或者其他的，只要是列表项的唯一标志）
  scrollTo(name) {
    let that = this;
    const query = wx.createSelectorQuery()
    query.select(".pro-item").boundingClientRect()
    //计算每一个item的高度（右侧分类的小标题高度是在css里写死的50px）
    query.exec(function(res) {
      that.moveHeight(res[0].height, name);
    })
  },

  moveHeight(height, name) {
    let list = this.data.serviceTypes;
    let top = 50; //右侧每一分类的标题名称的高度为50px，top记录每一个标题到顶部的距离
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].services.length; j++) {
        //如果当前的item是要滚动到顶部的，
        if (list[i].services[j].name == name) {
          this.setData({
            scrollTop: height * j + top
          })
          break;
        }
      }
      //右侧每划过一个分类，就把此分类的高度和标题的高度累加到top上
      top = top + list[i].services.length * height + 50;
    }
  },
  freeTell(e) {
    let mobile = e.currentTarget.dataset.mobile
    wx.makePhoneCall({
      phoneNumber: mobile,
      success: function() {
        

      },
      fail: function() {
        

      }

    })

  },


})